package com.ZeroCarbon.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ZeroCarbon.entity.RedisData;
import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * 缓存工具类
 *
 * @since 2024-10-11
 */
@Component
@RequiredArgsConstructor
public class CacheClient {

    /**
     * redis操作工具
     */
    private final StringRedisTemplate redis;

    /**
     * 内存重建线程池
     */
    private final static ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    /**
     * TTL写入缓存
     *
     * @param key  redis的key
     * @param data 数据
     * @param time 过期时间
     * @param unit 过期时间单位
     */
    public void set(String key, Object data, Long time, TimeUnit unit) {
        redis.opsForValue().set(key, JSONUtil.toJsonStr(data), time, unit);
    }

    //

    /**
     * 逻辑时间写入缓存
     *
     * @param key  redis的key
     * @param data 数据
     * @param time 过期时间
     * @param unit 过期时间单位
     */
    public void setWithLogicalExpire(String key, Object data, Long time, TimeUnit unit) {
        RedisData redisData = new RedisData();
        redisData.setData(data);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        redis.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    /**
     * 防止缓存击穿的查找
     *
     * @param keyPrefix  redis的key前缀
     * @param id         id
     * @param type       json转换为的类型
     * @param dbFallBack 数据库操作
     * @param time       设置防止缓存击穿的过期时间
     * @param unit       时间单位
     * @return 实体对象
     */
    public <R, ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallBack, Long time, TimeUnit unit) {
        String key = keyPrefix + id;
        String json = redis.opsForValue().get(key);
        if (StrUtil.isNotBlank(json)) {
            return JSONUtil.toBean(json, type);
        }
        //json可能为""
        if (json != null) {
            return null;
        }
        //以上操作说明redis缓存中不存在相应数据，查找数据库
        R data = dbFallBack.apply(id);
        if (data == null) {
            redis.opsForValue().set(key, "", time, unit);
            return null;
        }
        //如果数据库找得到则放入缓存
        this.set(key, data, time, unit);
        return data;
    }

    /**
     * 防止缓存击穿的查找
     *
     * @param keyPrefix  redis的key前缀
     * @param id         id
     * @param type       json转换为的类型
     * @param dbFallBack 数据库操作
     * @param time       设置逻辑过期时间
     * @param unit       时间单位
     */
    public <R, ID> R queryWithLogicalExpire(String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallBack, Long time, TimeUnit unit) {
        String key = keyPrefix + id;
        String json = redis.opsForValue().get(key);
        if (StrUtil.isBlank(json)) {
            return null;
        }
        //如果有这个key则需要判断是否逻辑过期
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        R data = JSON.parseObject(redisData.getData().toString(), type);
        LocalDateTime expireTime = redisData.getExpireTime();

        if (expireTime.isAfter(LocalDateTime.now())) {
            return data;
        }
        //设置锁的key
        String lockKey = "lock:" + keyPrefix + id;
        boolean isLock = tryLock(lockKey);

        //成功获取锁则进行更改过期的逻辑时间
        if (isLock) {
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    R newData = dbFallBack.apply(id);
                    //写入redis
                    this.setWithLogicalExpire(key, newData, time, unit);
                } catch (Exception e) {
                    throw new RuntimeException("Logical time update failed");
                } finally {
                    unlock(key);
                }
            });
        }
        return data;
    }

    /**
     * 加锁
     *
     * @param key 锁的key
     */
    private boolean tryLock(String key) {
        Boolean isLock = redis.opsForValue().setIfAbsent(key, "lock", 1, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(isLock);
    }

    /**
     * 释放锁
     *
     * @param key 锁的key
     */
    private void unlock(String key) {
        redis.delete(key);
    }
}
